<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="css/swiper.min.css" />
		<link href="css/gift.css" rel="stylesheet" />
	</head>

	<body>
		<!--页面标题栏开始-->
		<div class="mui-navbar-inner mui-bar mui-bar-nav">
			<h1 class="mui-center mui-title">徽章兑换</h1>
		</div>
		<div class="swiper-container" id="gifts"></div>

		<img id="back-btn" src="img/btn_back.png" class="mui-action-back" />

		<script id="gifts-tpl" type="text/html">
			<div class="swiper-wrapper">
				{{ each gifts as gift i }}
				<div class="swiper-slide">
					<img class="gift-cover" data-src="{{ gift.pic }}" />
					<p class="left-info">剩余{{ gift.left }}件</p>
					<h4>需要徽章</h4>
					<div class="badge-list" id="badge-list-{{ gift.id }}">
						{{ each gift.badges as badge j }}
						<div class="badge-item">
							{{ if badge.have }}
							<img src="{{ badge.pic_active }}" />
							<p class="have-badge">已获得</p>
							{{ else }}
							<img src="{{ badge.pic_disable }}" />
							<p>未获得</p>
							{{ /if }}
						</div>
						{{ /each }}
					</div>
					{{ if gift.get }} {{ if gift.scratched }}
					<a class="got-gift" data-id="{{ gift.id }}">抽奖完成</a> {{ else }}
					<a class="get-gift" data-id="{{ gift.id }}">马上抽奖</a> {{ /if }} {{ else }}
					<a class="get-no-gift">徽章不足</a> {{ /if }}
				</div>
				{{ /each }}
			</div>
			<div class="swiper-pagination"></div>
		</script>

		<script src="js/template.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/mui.min.js"></script>
		<script src="js/swiper.min.js" type="text/javascript"></script>
		<script src="js/av-mini-1.0.js"></script>
		<script>
			var appid = 'kou72um0ioak1kubrz0klwx8a7s3l261mgt54vbyotnblnby';
			var appkey = 'o56bexx1vr522x7ygfkvi7efvbhhmo6x2oaf3txb75wi2509';
			AV.initialize(appid, appkey);
			var Gift = AV.Object.extend('Gift');
			var Badge = AV.Object.extend('Badge');
			var swiper;
			var storage = window.localStorage;
			var user = AV.User.current();
			var load_img = function(i) {
				var eles = mui('img[data-src]');
				for (var i = 0; i < eles.length; i++) {
					var ele = eles[i];
					var url = ele.getAttribute('data-src');
					if (url == '') {
						continue;
					}
					var storage_key = 'img_' + url;
					if (storage_key in storage) {
						ele.setAttribute('src', storage[storage_key]);
					} else {
						ele.setAttribute('src', url);
						if (typeof(plus) != 'undefined') {
							(function(ele, url, storage_key) {
								plus.downloader.createDownload(url, {}, function(task, status) {
									if (status == 200) {
										//console.log("Download Pic Url: " + url)
										var local_url = plus.io.convertLocalFileSystemURL(task.filename);
										storage[storage_key] = local_url;
										ele.setAttribute('src', local_url);
									} else {
										console.log('download failed: ' + status);
									}
								}).start();
							})(ele, url, storage_key);
						} else {
						}
					}
					ele.removeAttribute('data-src');
				}
			}
			var load_gifts = function() {
				var gift_query = new AV.Query(Gift);
				gift_query.greaterThan('index', 0);
				gift_query.addAscending('index');
				gift_query.include('badges');
				gift_query.find().then(function(eles) {
					var gifts = []
					for (var i = 0; i < eles.length; i++) {
						var gift = eles[i];
						var badges = [];
						var get = true;
						var scratched = false;
						for (var j = 0; j < gift.get("badges").length; j++) {
							badge = gift.get("badges")[j];
							var have = false;
							if (storage["badge_" + badge.id]) {
								have = true;
							}
							if (!have) {
								get = false
							}
							badges.push({
								id: badge.id,
								name: badge.get("name"),
								pic_active: badge.get("picActive"),
								pic_disable: badge.get("picDisable"),
								hint: badge.get("hint"),
								info: badge.get("info"),
								have: have
							});
						};
						if (storage["scratch_" + gift.id] &&
							(storage["time_" + gift.id] > Date.parse(new Date()))) {
							scratched = true;
						}
						gifts.push({
							id: gift.id,
							index: gift.get("index"),
							pic: gift.get("pic"),
							winning: gift.get("winning"),
							rule: gift.get("rule"),
							left: gift.get("left"),
							badges: badges,
							get: get,
							scratched: scratched
						});
					}
					var gifts_html = template('gifts-tpl', {
						gifts: gifts
					});
					document.getElementById("gifts").innerHTML = gifts_html;
					load_img();
					swiper = new Swiper('.swiper-container', {
						loop: true,
						slidesPerView: 'auto',
						centeredSlides: true,
						pagination: '.swiper-pagination',
					});
					mui('body').on('tap', '.get-gift', function() {
						var gid = this.getAttribute('data-id');
						storage["scratch_" + gid] = true;
						storage["time_" + gid] = Date.parse(new Date()) + 86400000;
						var scratch = new Gift();
						scratch.id = gid;
						scratches = user.relation("scratches");
						scratches.add(scratch);
						user.save();
						mui.openWindow({
							id: 'scratch',
							url: 'scratch.html',
							styles: {
								top: 0,
								bottom: 0,
								bounce: "none",
							},
							extras: {
								gift_id: gid,
							},
							show: {
								autoShow: false,
							},
							waiting: {
								autoShow: true,
								title: "准备刮刮卡"
							}
						});
					});
					mui('body').on('tap', '.get-no-gift', function() {
						mui.toast("在首页寻找带徽章的话题去试试运气吧");
					});
					mui('body').on('tap', '.got-gift', function() {
						var id = this.getAttribute('data-id');
						var now = new Date();
						if (!storage["time_" + id]) {
							storage["time_" + id] = Date.parse(now) + 43200000;
						}
						var leave_0 = storage["time_" + id] - Date.parse(now);
						if (leave_0 > 0) {
							var leave_1 = leave_0 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
							var hours = Math.floor(leave_1 / (3600 * 1000))
								//计算相差分钟数
							var leave_2 = leave_1 % (3600 * 1000) //计算小时数后剩余的毫秒数
							var minutes = Math.floor(leave_2 / (60 * 1000))
							mui.toast("距离下次抽奖还有" + hours + "小时" + minutes + "分钟");
						} else {
							mui.toast("已重置，请关闭页面重新打开");
						}
					});
				});
			};
			mui.plusReady(function() {
				var topic_page = plus.webview.getWebviewById("topic");
				if (user) {
					for (var i = 0; i < storage.length; i++) {
						var storage_key = storage.key(i);
						if (/^badge_/g.test(storage_key) || /^scratch_/g.test(storage_key)) {
							delete storage[storage_key];
						}
					}
					var badges = user.relation("badges");
					badges.query().find({
						success: function(list) {
							for (var i = 0; i < list.length; i++) {
								storage["badge_" + list[i].id] = true;
							}
						}
					});
					var scratches = user.relation("scratches");
					scratches.query().find({
						success: function(list) {
							for (var i = 0; i < list.length; i++) {
								storage["scratch_" + list[i].id] = true;
							}
						}
					});
					load_gifts();
					plus.nativeUI.closeWaiting();
					plus.webview.currentWebview().show("pop-in");
				} else {
					plus.nativeUI.closeWaiting();
					topic_page.evalJS('mui("#badge").popover("toggle", {duration: "long"});mui.toast("校验失败，尚未登录");');
					plus.webview.currentWebview().close();
				}
			});
		</script>
	</body>

</html>